package com.ht.util;


import com.ht.constant.BusConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: UserUtil
 * @Description: 用户工具类
 */
@Component
public class UserUtil {
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private static HttpServletRequest request;
    @PostConstruct
    public void init(){
        UserUtil.request = httpServletRequest;
    }

    /**
     * 获取 request 里传递的 token
     *
     * @param request
     * @return
     */
    public static String getTokenByRequest(HttpServletRequest request) {
        String token = request.getParameter(BusConstant.TOKEN);
        if (token == null) {
            token = request.getHeader(BusConstant.X_ACCESS_TOKEN);
        }
        return token;
    }

    public static String getTokenByRequest() {
        String token = request.getParameter(BusConstant.TOKEN);
        if (token == null) {
            token = request.getHeader(BusConstant.X_ACCESS_TOKEN);
        }
        return token;
    }



    /*
     * @Author hejialun
     * @Description: TODO(获取用户id)
     * @date 2021/5/14 20:30
     * @return
     */
    public static String getUserId() {
        HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return JwtUtils.getKey(getTokenByRequest(request),"id");
    }




}